package com.godtree.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.godtree.dao.RankDataMapper;
import com.godtree.model.RankData;
import com.godtree.model.RankDataMapping;
import com.godtree.dao.RankDataMappingMapper;
import com.godtree.service.IRankDataMappingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.godtree.service.IRankDataService;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lisicheng
 * @since 2022-08-03
 */
@Service
@RequiredArgsConstructor
public class RankDataMappingServiceImpl extends
    ServiceImpl<RankDataMappingMapper, RankDataMapping> implements IRankDataMappingService {

  private final RankDataMapper rankDataMapper;
  private final IRankDataService rankDataService;

  @Override
  public void refreshRankDataMapping() {

    // 昨天的日期
    DateTime date = DateUtil.offsetDay(DateUtil.beginOfDay(DateUtil.date()), -1);
    // 初始化起始页
    int index = 1;
    // 循环查询
    while (true) {

      // 分页查询

      List<RankDataMapping> records = page(new Page<>(index++, 1000),
          Wrappers.<RankDataMapping>lambdaQuery()
              .ge(RankDataMapping::getUpdateTime, date)).getRecords();
      // 如果没有数据，跳出循环
      if (records.isEmpty()) {
        break;
      }

      // 根据映射数据的rankId和name查询rankData
      List<RankData> rankDataList = rankDataMapper.selectList(
          Wrappers.<RankData>lambdaQuery().select(RankData::getId, RankData::getName)
              .in(RankData::getRanks,
                  records.stream().map(RankDataMapping::getRankId).distinct()
                      .collect(Collectors.toList()))
              .in(RankData::getName, records.stream().map(RankDataMapping::getName).distinct()
                  .collect(Collectors.toList())));

      // 如果没有数据，下次循环
      if (rankDataList.isEmpty()) {
        continue;
      }

      // 将映射数据转换为map
      // key: name value: alias
      Map<String, String> rankDataMappingMap = records.stream()
          .collect(Collectors.toMap(RankDataMapping::getName, RankDataMapping::getAlias));

      // 根据映射数据更新rankData
      // 如果rankData的name在映射数据中存在，就更新rankData的name为映射数据的alias
      rankDataList.stream().filter(item -> rankDataMappingMap.containsKey(item.getName()))
          .forEach(item -> {
            item.setName(rankDataMappingMap.get(item.getName()));
            item.setFullPinyinName(PinyinUtil.getPinyin(item.getName(), ""));
            item.setSimplePinyinName(PinyinUtil.getFirstLetter(item.getName(), ""));
          });

      // 批量更新rankData
      rankDataService.updateBatchById(rankDataList);

    }

  }
}
